{% extends 'base.html' %}
{% load static %}

{% block title %}结算 - 商城系统{% endblock %}

{% block extra_css %}
<style>
    .checkout-container {
        background-color: #f8f9fa;
        padding: 30px 0;
        min-height: 70vh;
    }
    
    .checkout-card {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,.1);
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .checkout-title {
        font-size: 1.2rem;
        font-weight: 600;
        margin-bottom: 20px;
        color: #333;
        position: relative;
        padding-bottom: 10px;
    }
    
    .checkout-title:after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 50px;
        height: 3px;
        background-color: #0d6efd;
    }
    
    .checkout-address-item {
        border: 1px solid #e0e0e0;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all .2s ease;
        position: relative;
    }
    
    .checkout-address-item:hover {
        border-color: #aaa;
    }
    
    .checkout-address-item.selected {
        border-color: #0d6efd;
        background-color: #f0f7ff;
    }
    
    .address-select-indicator {
        position: absolute;
        top: 10px;
        right: 10px;
        width: 20px;
        height: 20px;
        border: 2px solid #ddd;
        border-radius: 50%;
    }
    
    .checkout-address-item.selected .address-select-indicator {
        background-color: #0d6efd;
        border-color: #0d6efd;
    }
    
    .checkout-address-item.selected .address-select-indicator:after {
        content: '';
        position: absolute;
        top: 4px;
        left: 4px;
        width: 8px;
        height: 8px;
        background-color: #fff;
        border-radius: 50%;
    }
    
    .empty-address-tip {
        background-color: #fff3cd;
        border-left: 4px solid #ffc107;
        padding: 10px 15px;
        color: #856404;
    }
    
    .product-list {
        max-height: 400px;
        overflow-y: auto;
    }
    
    .product-item {
        padding: 15px 0;
        border-bottom: 1px solid #eee;
    }
    
    .product-item:last-child {
        border-bottom: none;
    }
    
    .product-img {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 4px;
    }
    
    .product-info {
        flex: 1;
    }
    
    .product-name {
        font-size: 16px;
        margin-bottom: 8px;
        color: #333;
    }
    
    .product-price {
        font-size: 16px;
        color: #e4393c;
        font-weight: 600;
    }
    
    .product-quantity {
        color: #666;
    }
    
    .payment-method {
        display: block;
        border: 1px solid #e0e0e0;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all .2s ease;
        position: relative;
    }
    
    .payment-method:hover {
        border-color: #aaa;
    }
    
    .payment-method.selected {
        border-color: #0d6efd;
        background-color: #f0f7ff;
    }
    
    .payment-method-icon {
        font-size: 24px;
        margin-right: 10px;
        color: #666;
    }
    
    .payment-method.selected .payment-method-icon {
        color: #0d6efd;
    }
    
    .order-summary {
        position: sticky;
        top: 20px;
    }
    
    .summary-row {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px dashed #eee;
    }
    
    .summary-row.total {
        border-top: 1px solid #ddd;
        border-bottom: none;
        padding-top: 15px;
        margin-top: 10px;
        font-weight: 600;
        font-size: 18px;
    }
    
    .summary-row.total .summary-value {
        color: #e4393c;
    }
    
    .btn-submit {
        width: 100%;
        padding: 12px;
        font-size: 16px;
        margin-top: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="checkout-container py-4">
    <div class="container">
        <h2 class="mb-4">确认订单</h2>
        
        <div class="row">
            <!-- 左侧主要内容 -->
            <div class="col-lg-8">
                <!-- 收货地址 -->
                <div class="checkout-card">
                    <h3 class="checkout-title">收货地址</h3>
                    
                    {% if addresses %}
                        <div class="address-list">
                            {% for address in addresses %}
                                <div class="checkout-address-item {% if address.is_default %}selected{% endif %}" data-address-id="{{ address.id }}">
                                    <span class="address-select-indicator"></span>
                                    
                                    <div class="address-info">
                                        <h6>{{ address.receiver }} <span class="badge bg-light text-dark">{{ address.phone }}</span></h6>
                                        <p class="mb-1">{{ address.province }} {{ address.city }} {{ address.district }} {{ address.street|default:'' }}</p>
                                        <p class="mb-1">{{ address.address }}</p>
                                        {% if address.zip_code %}
                                        <p class="mb-0 text-muted small">邮编：{{ address.zip_code }}</p>
                                        {% endif %}
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                        <div class="mt-3">
                            <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addressModal">
                                <i class="bi bi-plus-circle"></i> 新增收货地址
                            </button>
                        </div>
                    {% else %}
                        <div class="empty-address-tip">
                            <p class="mb-0"><i class="bi bi-exclamation-triangle"></i> 您还没有添加收货地址，请先添加地址</p>
                        </div>
                        <div class="mt-3">
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addressModal">
                                <i class="bi bi-plus-circle"></i> 添加收货地址
                            </button>
                        </div>
                    {% endif %}
                </div>
                
                <!-- 商品清单 -->
                <div class="checkout-card">
                    <h3 class="checkout-title">商品清单</h3>
                    
                    <div class="product-list">
                        {% for item in cart_items %}
                            <div class="product-item d-flex">
                                <img src="{{ item.product.get_main_image_url }}" alt="{{ item.product.name }}" class="product-img me-3">
                                <div class="product-info">
                                    <h5 class="product-name">{{ item.product.name }}</h5>
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <span class="product-price">¥{{ item.product.price }}</span>
                                        </div>
                                        <div class="product-quantity">x{{ item.quantity }}</div>
                                    </div>
                                    <!-- 添加库存信息显示 -->
                                    {% if item.product.stock < item.quantity %}
                                    <div class="text-danger mt-1">
                                        <small><i class="bi bi-exclamation-triangle-fill"></i> 库存不足！当前库存：{{ item.product.stock }}件</small>
                                    </div>
                                    {% elif item.product.stock <= 0 %}
                                    <div class="text-danger mt-1">
                                        <small><i class="bi bi-x-circle-fill"></i> 已售罄</small>
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
                
                <!-- 支付方式 -->
                <div class="checkout-card">
                    <h3 class="checkout-title">支付方式</h3>
                    
                    <div class="payment-methods">
                        <label class="payment-method selected" data-payment="alipay">
                            <input type="radio" name="payment_method" value="alipay" checked hidden>
                            <div class="d-flex align-items-center">
                                <i class="bi bi-credit-card payment-method-icon"></i>
                                <div>
                                    <h6 class="mb-0">支付宝</h6>
                                    <p class="mb-0 text-muted small">推荐支付宝用户使用</p>
                                </div>
                            </div>
                        </label>
                        
                        <label class="payment-method" data-payment="wechat">
                            <input type="radio" name="payment_method" value="wechat" hidden>
                            <div class="d-flex align-items-center">
                                <i class="bi bi-chat-square payment-method-icon"></i>
                                <div>
                                    <h6 class="mb-0">微信支付</h6>
                                    <p class="mb-0 text-muted small">推荐微信用户使用</p>
                                </div>
                            </div>
                        </label>
                        
                        <label class="payment-method" data-payment="bank">
                            <input type="radio" name="payment_method" value="bank" hidden>
                            <div class="d-flex align-items-center">
                                <i class="bi bi-bank payment-method-icon"></i>
                                <div>
                                    <h6 class="mb-0">银行卡支付</h6>
                                    <p class="mb-0 text-muted small">支持大多数银行卡</p>
                                </div>
                            </div>
                        </label>
                        
                        <label class="payment-method" data-payment="cod">
                            <input type="radio" name="payment_method" value="cod" hidden>
                            <div class="d-flex align-items-center">
                                <i class="bi bi-cash payment-method-icon"></i>
                                <div>
                                    <h6 class="mb-0">货到付款</h6>
                                    <p class="mb-0 text-muted small">收到商品后再付款</p>
                                </div>
                            </div>
                        </label>
                    </div>
                </div>
                
                <!-- 订单备注 -->
                <div class="checkout-card">
                    <h3 class="checkout-title">订单备注</h3>
                    
                    <div class="form-group">
                        <textarea id="order_remark" class="form-control" rows="3" placeholder="选填，可以告诉我们您的特殊要求"></textarea>
                    </div>
                </div>
            </div>
            
            <!-- 右侧订单摘要 -->
            <div class="col-lg-4">
                <div class="checkout-card order-summary">
                    <h3 class="checkout-title">订单摘要</h3>
                    
                    <div class="summary-row">
                        <span class="summary-label">商品总价</span>
                        <span class="summary-value">¥{{ total_price }}</span>
                    </div>
                    
                    <div class="summary-row">
                        <span class="summary-label">运费</span>
                        <span class="summary-value">¥{{ shipping_fee|default:"0.00" }}</span>
                    </div>
                    
                    <div class="summary-row">
                        <span class="summary-label">优惠</span>
                        <span class="summary-value">- ¥{{ discount|default:"0.00" }}</span>
                    </div>
                    
                    <div class="summary-row total">
                        <span class="summary-label">应付总额</span>
                        <span class="summary-value">¥{{ final_total_price }}</span>
                    </div>
                    
                    <form id="orderForm" method="post" action="{% url 'create_order' %}" onsubmit="return validateOrderForm()">
                        {% csrf_token %}
                        <input type="hidden" name="address_id" id="selected_address_id" value="{{ default_address.id|default:'' }}">
                        <input type="hidden" name="payment_method" id="selected_payment_method" value="alipay">
                        <input type="hidden" name="remark" id="order_remark_value" value="">
                        
                        {% if buy_now %}
                        <input type="hidden" name="buy_now" value="true">
                        <input type="hidden" name="buy_now_product_id" value="{{ buy_now_product_id }}">
                        <input type="hidden" name="buy_now_quantity" value="{{ buy_now_quantity }}">
                        {% endif %}
                        
                        <button type="submit" class="btn btn-danger btn-submit" id="submit-order-btn" {% if not addresses %}disabled{% endif %}>
                            提交订单
                        </button>
                    </form>
                    
                    {% if not addresses %}
                    <div class="mt-2 text-center text-muted small">
                        <i class="bi bi-info-circle"></i> 请先添加收货地址后再提交订单
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 在页面底部添加地址模态框 -->
<!-- 地址表单模态框 -->
<div class="modal fade" id="addressModal" tabindex="-1" aria-labelledby="addressModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addressModalLabel">添加新地址</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addressForm" method="post" action="{% url 'add_address_checkout' %}">
                    {% csrf_token %}
                    <input type="hidden" name="address_id" id="address_id" value="">
                    
                    <div class="mb-3">
                        <label for="id_receiver" class="form-label">收货人</label>
                        <input type="text" class="form-control" id="id_receiver" name="receiver" placeholder="请输入收货人姓名" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="id_province" class="form-label">省份</label>
                            <select class="form-select" id="id_province" name="province" required>
                                <option value="">请选择省份</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="id_city" class="form-label">城市</label>
                            <select class="form-select" id="id_city" name="city" required>
                                <option value="">请选择城市</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="id_district" class="form-label">区/县</label>
                            <select class="form-select" id="id_district" name="district" required>
                                <option value="">请选择区/县</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="id_address" class="form-label">详细地址</label>
                        <input type="text" class="form-control" id="id_address" name="address" placeholder="详细地址，如街道、门牌号等" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="id_phone" class="form-label">联系电话</label>
                            <input type="text" class="form-control" id="id_phone" name="phone" placeholder="手机号码" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="id_zip_code" class="form-label">邮政编码</label>
                            <input type="text" class="form-control" id="id_zip_code" name="zip_code" placeholder="可选">
                        </div>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="id_is_default" name="is_default">
                        <label class="form-check-label" for="id_is_default">设为默认地址</label>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'js/area_data_full.js' %}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化省市区选择器
        initAreaSelector();
        
        // 地址选择
        initAddressSelection();
        
        // 支付方式选择
        initPaymentMethodSelection();
        
        // 绑定地址选择变化事件
        checkAddressSelection();
        
        // 提交订单时，将备注内容添加到隐藏字段
        const orderForm = document.getElementById('orderForm');
        const orderRemarkTextarea = document.getElementById('order_remark');
        const orderRemarkValue = document.getElementById('order_remark_value');
    });
    
    // 检查地址选择状态，启用或禁用提交按钮
    function checkAddressSelection() {
        const submitBtn = document.getElementById('submit-order-btn');
        if (selectedAddressInput && selectedAddressInput.value && selectedAddressInput.value.trim() !== '') {
            submitBtn.disabled = false;
        } else {
            submitBtn.disabled = true;
        }
    }
    
    // 表单验证函数
    function validateOrderForm() {
        // 更新备注
        const orderRemarkTextarea = document.getElementById('order_remark');
        const orderRemarkValue = document.getElementById('order_remark_value');
        orderRemarkValue.value = orderRemarkTextarea.value;
        
        // 检查是否选择了地址
        if (!selectedAddressInput || !selectedAddressInput.value || selectedAddressInput.value.trim() === '') {
            if (typeof showToast === 'function') {
                showToast('请选择收货地址！', 'danger');
            } else {
                alert('请选择收货地址！');
            }
            return false;
        }
        
        // 检查商品是否有库存问题
        const stockWarnings = document.querySelectorAll('.text-danger');
        if (stockWarnings.length > 0) {
            const confirmSubmit = confirm('部分商品存在库存问题，确定要继续下单吗？提交后系统将进行最终库存校验。');
            if (!confirmSubmit) {
                return false;
            }
        }
        
        return true;
    }
    
    // 初始地址选择变量
    let selectedAddressInput;
    
    // 初始化地址选择功能
    function initAddressSelection() {
        selectedAddressInput = document.getElementById('selected_address_id');
        const addressItems = document.querySelectorAll('.checkout-address-item');
        
        // 如果没有选中的地址但有地址项，自动选择第一个
        let hasSelectedAddress = false;
        
        addressItems.forEach((item, index) => {
            // 检查是否有默认选中的地址
            if (item.classList.contains('selected')) {
                hasSelectedAddress = true;
                // 确保hidden input值与选中的地址匹配
                selectedAddressInput.value = item.dataset.addressId;
            }
            
            item.addEventListener('click', function() {
                // 移除所有选中状态
                addressItems.forEach(addr => addr.classList.remove('selected'));
                
                // 设置当前地址为选中
                this.classList.add('selected');
                
                // 更新隐藏输入框的值
                selectedAddressInput.value = this.dataset.addressId;
                
                // 检查地址选择状态
                checkAddressSelection();
            });
        });
        
        // 如果没有选中地址但有地址项，自动选择第一个
        if (!hasSelectedAddress && addressItems.length > 0) {
            const firstAddressItem = addressItems[0];
            firstAddressItem.classList.add('selected');
            selectedAddressInput.value = firstAddressItem.dataset.addressId;
            
            // 在控制台输出调试信息
            console.log('已自动选择第一个地址:', firstAddressItem.dataset.addressId);
        }
        
        // 如果此时仍然没有选中的地址但有地址项，尝试再次强制选择第一个
        if ((!selectedAddressInput.value || selectedAddressInput.value.trim() === '') && addressItems.length > 0) {
            const firstAddress = addressItems[0];
            firstAddress.classList.add('selected');
            selectedAddressInput.value = firstAddress.dataset.addressId;
            console.log('强制选择第一个地址:', firstAddress.dataset.addressId);
        }
        
        // 初始检查地址选择状态
        checkAddressSelection();
    }
    
    // 刷新地址列表
    function refreshAddressList() {
        fetch('{% url "get_addresses" %}')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 获取地址列表容器
                    const addressListContainer = document.querySelector('.address-list');
                    if (!addressListContainer) {
                        location.reload(); // 如果没有容器（首次添加地址），刷新页面
                        return;
                    }
                    
                    // 保存当前选中的地址ID（如果有）
                    const currentSelectedId = selectedAddressInput ? selectedAddressInput.value : '';
                    
                    // 清空当前地址列表
                    addressListContainer.innerHTML = '';
                    
                    // 标记是否有默认地址
                    let hasDefaultAddress = false;
                    // 标记是否在新地址列表中找到之前选中的地址
                    let foundPreviousSelected = false;
                    
                    // 添加新的地址项
                    data.addresses.forEach(address => {
                        // 判断是否为默认地址或之前选中的地址
                        let isSelected = false;
                        
                        if (address.is_default) {
                            isSelected = true;
                            hasDefaultAddress = true;
                        }
                        
                        if (currentSelectedId && address.id.toString() === currentSelectedId.toString()) {
                            isSelected = true;
                            foundPreviousSelected = true;
                        }
                        
                        const isSelectedClass = isSelected ? 'selected' : '';
                        const defaultBadge = address.is_default ? 
                            '<span class="address-default-badge">默认地址</span>' : '';
                        const zipCode = address.zip_code ? 
                            `<p class="mb-0 text-muted small">邮编：${address.zip_code}</p>` : '';
                            
                        const addressHtml = `
                            <div class="checkout-address-item ${isSelectedClass}" data-address-id="${address.id}">
                                <span class="address-select-indicator"></span>
                                
                                <div class="address-info">
                                    <h6>${address.receiver} <span class="badge bg-light text-dark">${address.phone}</span></h6>
                                    <p class="mb-1">${address.province} ${address.city} ${address.district} ${address.street || ''}</p>
                                    <p class="mb-1">${address.address}</p>
                                    ${zipCode}
                                </div>
                            </div>
                        `;
                        
                        addressListContainer.insertAdjacentHTML('beforeend', addressHtml);
                    });
                    
                    // 重新初始化地址选择功能
                    initAddressSelection();
                    
                    // 确保提交按钮状态更新
                    checkAddressSelection();
                } else {
                    if (typeof showToast === 'function') {
                        showToast('获取地址列表失败，请刷新页面重试', 'danger');
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                if (typeof showToast === 'function') {
                    showToast('获取地址列表失败，请刷新页面重试', 'danger');
                }
            });
    }
    
    // 初始化省市区选择器
    function initAreaSelector() {
        const provinceSelect = document.getElementById('id_province');
        const citySelect = document.getElementById('id_city');
        const districtSelect = document.getElementById('id_district');
        
        // 检查是否需要创建街道选择框
        let streetSelect = document.getElementById('id_street');
        if (!streetSelect) {
            // 创建街道选择框
            const districtGroup = document.getElementById('id_district').closest('.mb-3');
            if (districtGroup) {
                const streetGroup = document.createElement('div');
                streetGroup.className = 'mb-3';
                streetGroup.innerHTML = `
                    <label for="id_street" class="form-label">街道/乡镇</label>
                    <select class="form-select" id="id_street" name="street">
                        <option value="">请选择街道/乡镇</option>
                    </select>
                `;
                districtGroup.parentNode.insertBefore(streetGroup, districtGroup.nextSibling);
                streetSelect = document.getElementById('id_street');
            }
        }
        
        // 加载省份数据
        provinceSelect.innerHTML = '<option value="">请选择省份</option>';
        for (const province in areaData) {
            const option = document.createElement('option');
            option.value = province;
            option.textContent = province;
            provinceSelect.appendChild(option);
        }
        
        // 省份变化时更新城市
        provinceSelect.addEventListener('change', function() {
            // 清空城市、区县和街道下拉框
            citySelect.innerHTML = '<option value="">请选择城市</option>';
            districtSelect.innerHTML = '<option value="">请选择区/县</option>';
            if (streetSelect) {
                streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
            }
            
            const selectedProvince = this.value;
            if (selectedProvince && areaData[selectedProvince]) {
                // 加载选定省份的城市
                for (const city in areaData[selectedProvince]) {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;
                    citySelect.appendChild(option);
                }
            }
        });
        
        // 城市变化时更新区县
        citySelect.addEventListener('change', function() {
            // 清空区县和街道下拉框
            districtSelect.innerHTML = '<option value="">请选择区/县</option>';
            if (streetSelect) {
                streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
            }
            
            const selectedProvince = provinceSelect.value;
            const selectedCity = this.value;
            
            if (selectedProvince && selectedCity && 
                areaData[selectedProvince] && 
                areaData[selectedProvince][selectedCity]) {
                // 加载选定城市的区县
                const districts = areaData[selectedProvince][selectedCity];
                // 修复: 使用for...in循环替代forEach
                for (const district in districts) {
                    const option = document.createElement('option');
                    option.value = district;
                    option.textContent = district;
                    districtSelect.appendChild(option);
                }
            }
        });
        
        // 区县变化时更新街道
        districtSelect.addEventListener('change', function() {
            // 清空街道下拉框
            if (streetSelect) {
                streetSelect.innerHTML = '<option value="">请选择街道/乡镇</option>';
                
                const selectedProvince = provinceSelect.value;
                const selectedCity = citySelect.value;
                const selectedDistrict = this.value;
                
                if (selectedProvince && selectedCity && selectedDistrict && 
                    areaData[selectedProvince] && 
                    areaData[selectedProvince][selectedCity] &&
                    areaData[selectedProvince][selectedCity][selectedDistrict]) {
                    // 加载选定区县的街道
                    const streets = areaData[selectedProvince][selectedCity][selectedDistrict];
                    // 检查streets是否为数组
                    if (Array.isArray(streets)) {
                        // 如果是数组，直接遍历数组元素
                        streets.forEach(street => {
                            const option = document.createElement('option');
                            option.value = street;
                            option.textContent = street;
                            streetSelect.appendChild(option);
                        });
                    } else {
                        // 如果是对象，遍历对象的键
                        for (const street in streets) {
                            const option = document.createElement('option');
                            option.value = street;
                            option.textContent = street;
                            streetSelect.appendChild(option);
                        }
                    }
                }
            }
        });
    }
    
    // 初始化支付方式选择
    function initPaymentMethodSelection() {
        const paymentMethods = document.querySelectorAll('.payment-method');
        const selectedPaymentInput = document.getElementById('selected_payment_method');
        const currentPaymentMethod = selectedPaymentInput.value || 'alipay';
        
        // 确保有默认选中的支付方式
        let hasSelectedPayment = false;
        
        paymentMethods.forEach(method => {
            const radioInput = method.querySelector('input[type="radio"]');
            
            // 如果当前支付方式与保存的值匹配，选中它
            if (radioInput && radioInput.value === currentPaymentMethod) {
                method.classList.add('selected');
                radioInput.checked = true;
                hasSelectedPayment = true;
            }
            
            method.addEventListener('click', function() {
                // 移除所有选中状态
                paymentMethods.forEach(pm => pm.classList.remove('selected'));
                
                // 设置当前支付方式为选中
                this.classList.add('selected');
                
                // 更新隐藏输入框的值
                const radioInput = this.querySelector('input[type="radio"]');
                radioInput.checked = true;
                selectedPaymentInput.value = radioInput.value;
            });
        });
        
        // 如果没有选中的支付方式，选择第一个
        if (!hasSelectedPayment && paymentMethods.length > 0) {
            const firstPaymentMethod = paymentMethods[0];
            firstPaymentMethod.classList.add('selected');
            const radioInput = firstPaymentMethod.querySelector('input[type="radio"]');
            if (radioInput) {
                radioInput.checked = true;
                selectedPaymentInput.value = radioInput.value;
            }
        }
    }
    
    // 处理地址表单提交
    const addressForm = document.getElementById('addressForm');
    if (addressForm) {
        addressForm.addEventListener('submit', function(event) {
            event.preventDefault();
            
            // 使用Fetch API提交表单
            fetch(this.action, {
                method: 'POST',
                body: new FormData(this),
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                // 关闭模态框
                const addressModal = bootstrap.Modal.getInstance(document.getElementById('addressModal'));
                addressModal.hide();
                
                // 重置表单
                this.reset();
                
                // 刷新地址列表
                refreshAddressList();
                
                // 显示成功消息
                if (typeof showToast === 'function') {
                    showToast('地址添加成功！', 'success');
                } else {
                    alert('地址添加成功！');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                if (typeof showToast === 'function') {
                    showToast('添加地址失败，请重试！', 'danger');
                } else {
                    alert('添加地址失败，请重试！');
                }
            });
        });
    }
</script>
{% endblock %} 